package admin.controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.forms.MetaSeoForm;
import admin.models.MetaSeoModel;

import entities.MetaSeo;

public class MetaSeoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get(name);
		
		if (metaseo == null) {
			metaseo = new MetaSeo();
			metaseo.setId(name);
		}
		
		request.setAttribute("metaseo", metaseo);
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		try {
			request.getRequestDispatcher("/admin/pages/meta_seo_form.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
		MetaSeo metaseo = metaseoModel.get(name);
		
		if (metaseo == null) {
			metaseo = new MetaSeo();
			metaseo.setId(name);
		}
		
		//Check value valid form
		TreeMap<String, Object> forms = (TreeMap<String, Object>) MetaSeoForm.checkValid(request, metaseo); 
		metaseo = (MetaSeo) forms.get("metaseo");
		TreeMap<String, String> check = (TreeMap<String, String>) forms.get("checkValid");
		
		if (check.size() == 0) {
			metaseoModel.insert(metaseo);
			request.setAttribute("success", "Change data sucess.");
		}
		
		request.setAttribute("metaseo", metaseo);
		request.setAttribute("check", check);
		request.setAttribute("name", name);
		try {
			request.getRequestDispatcher("/admin/pages/meta_seo_form.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
